When we created Person we directly included address information into them. This is alright, but what if we want to use Address in another class? Let's introduce a new entity, Address, and make it embedded. This means its fields will end up as columns in the table of the entity that contains it.
Sure enough, if you review PersonTest.java, it no longer compiles. Before we go any further, let's update it to get it to compile and then verify that the unit tests still pass.
Replace the following two lines:
privatefinal Person p1 = new Person("Brett", 'L', "Schuchert", "Street1",
"Street2", "City", "State", "Zip");privatefinal Person p2 = new Person("FirstName", 'K', "LastName",
"Street1", "Street2", "City", "State", "Zip");
with the following four lines
privatefinal Address a1 = new Address("A Rd.", "", "Dallas", "TX", "75001");privatefinal Person p1 = new Person("Brett", 'L', "Schuchert", a1);privatefinal Address a2 = new Address("B Rd.", "S2", "OkC", "OK", "73116");privatefinal Person p2 = new Person("FirstName", 'K', "LastName", a2);
Rerun your tests (Ctrl-F11) and make sure everything is all green.
Next, we want to verify that the address we persist is in the database. Update the unit test method as follows:
PersonTest#insertAndRetrieve
@SuppressWarnings("unchecked")
@Test
publicvoid insertAndRetrieve(){
em.getTransaction().begin();
em.persist(p1);
em.persist(p2);
em.getTransaction().commit();finalList<Person> list = em.createQuery("select p from Person p")
.getResultList();
assertEquals(2, list.size());for(Person current : list){finalString firstName = current.getFirstName();finalString streetAddress1 = current.getAddress()
.getStreetAddress1();
assertTrue(firstName.equals("Brett")
|| firstName.equals("FirstName"));
assertTrue(streetAddress1.equals("A Rd.")
|| streetAddress1.equals("B Rd."));}}
First, we'll create Address:
Address.java
Next, we need to update Person (doing so will cause our unit test class to no longer compile):
Person.java
Sure enough, if you review PersonTest.java, it no longer compiles. Before we go any further, let's update it to get it to compile and then verify that the unit tests still pass.
Replace the following two lines:
with the following four lines
Rerun your tests (Ctrl-F11) and make sure everything is all green.
Next, we want to verify that the address we persist is in the database. Update the unit test method as follows:
PersonTest#insertAndRetrieve
Run your program and make sure it's all green.